var _Global_Data = {

    "machine_infos" : [],  //本地存储的机器信息数组

    "all_products" : {},     //全部商品

    "opto" : {}, //眼镜参数

    "replenishment_clerks" : {},    //补货员信息

    "colors" : [],           //产品的全部颜色

    "current_aisle" : '',        //当前货道

    "selected_machine_id" : '',      //选中的机器的id

    "selected_replenishment_id" : '',     //选中的补货员id

    "selected_machine_aisles" : [],  //被选中的机器的货道信息

    "product_type" : 'Glass',        //选中的产品的类别

    "selected_product_id" : '',     //选中的产品id

    "selected_color_id" : '',         //选中的颜色id

    "selected_task_id" : '',        //当前查看的任务清单id

    "tasks" : {},                   //本地存储的清单列表

    "task_details" : [],             //任务清单详情

    "current_product_has_rd": false,     // 当前的商品是否有度数

    "selected_rd": '',                  // 球光镜

    "selected_as": "",                  // 柱光镜

    "selected_axis": "",            // 轴位

    current_product_has_rd: false,

    "task_status" : {

        0 : '未完成补货',

        1 : '完成补货'

    }                               //清单状态映射表

};


var _EMPTY = '无';

var ReplenishResource = new Resource( API_LIST.REPLENISH_LIST , Vue.http);

var ProductColorResource = new Resource( API_LIST.AISLE_PRODUCT_COLOR , Vue.http);

!function reviseAisle() {

    Vue.directive('max-value', {
        bind : function (el,binding) {

            el.handler = function () {

                var max_value = binding.value.max_count - binding.value.current_count;

                var int_value = parseInt(el.value);

                if ( int_value !== int_value ) {
                    el.value = 0;
                } else if ( int_value > max_value ) {
                    el.value = max_value;
                } else {
                    el.value = int_value;
                }

            };


            el.addEventListener('input', el.handler );
            el.addEventListener('blur', el.handler );
        },
        unbind : function (el) {

            el.removeEventListener('input', el.handler);
            el.removeEventListener('blur', el.handler);
        }
    });

    var vm = new Vue({

        el : "#dashboard",

        data : _Global_Data,

        created : function(){

            var self = this;

            self.listRequest();

            self.initData()
                .then(function(succeed){

                    if(succeed){
                        //给select2设置初始值
                        $("#machine_select").val(self.selected_machine_id).trigger('change');
                    }

                });

        },

        computed : {

            //商品类型判断
            productJudge : function productJudge(){

                if ( this.product_type == 'Glass' ||
                    this.product_type == 'Lens' ||
                    this.product_type == 'BeautyContactLens') {
                    return true;
                }else {
                    return false
                }

            },

            // 隐形眼镜类型
            isContactLens: function () {
                return (this.product_type === 'TransparentContactLens' || this.product_type === 'BeautyContactLens')
            },

            // 透明隐形眼镜
            isTransparentContactLens: function () {
                return this.product_type === 'TransparentContactLens';
            },

            isBeautyContactLens: function () {
                return this.product_type === 'BeautyContactLens';
            },

            // 镜片
            isLens: function () {
                return this.product_type === 'Lens';
            },

            isGlass: function () {
                return this.product_type === 'Glass';
            },

            isNursingSupply: function (){
                return this.product_type === 'NursingSupply';
            },

            hasRd: function () {
                return !( this.isNursingSupply || (this.isGlass && !this.current_product_has_rd) )
            }

        },

        methods : {

            /**
             * 选择球镜的回调
             * @param {object} event
             */
            selectRd: function (event) {
                this.selected_rd = event.target.value.toString();
            },

            /**
             * 选柱镜的回调
             * @param {object} event
             */
            selectAs: function (event) {
                this.selected_as = event.target.value.toString();
            },

            /**
             * 选轴位的回调
             * @param {object} event
             */
            selectAxis: function (event) {
                this.selected_axis = event.target.value.toString();

            },

            /**
             * 设置眼镜的数据, 默认设置option的第一项
             * @return {undefined}
             */
            setOptionOfProduct: function (rd, as, axis) {

                if( this.isGlass) {
                    rd = this.isEmpty(rd) ? this.opto.sph[0] : String(rd);
                    $("select.select2_rd").val(rd).trigger('change');
                    this.selected_rd = rd;

                    if (this.isContactLens) return;  // 隐形眼镜不设置以下选项

                    as = this.isEmpty(as) ? this.opto.cyl[0] : String(as);
                    $('.select2_as').val(as).trigger('change');
                    this.selected_as = as;

                    if (this.isLens) return; // 镜片眼镜不设置以下选项

                    axis = this.isEmpty(axis) ?  this.opto.axis[0] :String(axis);
                    $('.select2_axis').val(axis).trigger('change');
                    this.selected_axis =axis;
                }
            },

            /**
             * 判断是否为null
             * @param val
             * @return {boolean}
             */
            isEmpty: function (val) {
                return  (typeof val === 'object' && !val) || (val === _EMPTY);
            },

            //点击选择机器型号
            showType : function showType( e ) {

                if( this.selected_machine_id == e.target.value ) return;

                this.selected_machine_id = e.target.value;

                if( this.selected_machine_id == '' ) return;

                this.aisleRequest(this.selected_machine_id);

            },
            //点击选择补货员
            replenishmentSelect : function replenishmentSelect( e ){

                this.selected_replenishment_id = e.target.value;

            },
            //商品类型选择
            glassTypeSelect : function glassTypeSelect( e ) {

                if( this.product_type == e.target.value ) return;

                this.product_type = e.target.value;

                $('.product_select').val('').trigger('change');

                $('.color_select').val('').trigger('change');

            },
            //点击选择商品
            productSelect : function productSelect( e ) {

                if( this.selected_product_id == e.target.value ) return;

                this.selected_product_id = e.target.value;

                if( this.product_type == 'TransparentContactLens' || this.product_type == 'NursingSupply' ) return;

                var self = this;

                this.getProductColor( self.selected_product_id,self.product_type )
                    .then(function(succeed){

                        if(succeed){

                            $('.color_select').val(self.colors[0].id).trigger('change');
                            self.selected_color_id =  self.colors[0].id;

                        }

                    });

                self.selected_rd = self.opto.sph[0];
                self.selected_as = self.opto.cyl[0];
                self.selected_axis = self.opto.axis[0];
                self.setOptionOfProduct(self.selected_rd, self.selected_as, self.selected_axis);

            },
            //颜色选择
            colorSelect : function colorSelect( e ) {
                this.selected_color_id =  e.target.value;
                $('.color_select').val(this.selected_color_id).trigger('change');

            },
            //最大补货数量限制
            stockCount : function stockCount( aisle ){

                return aisle.max_count - aisle.current_count;

            },
            //点击设置货道商品的方法
            reviseProduct : function reviseProduct( id ) {

                var self = this;

                self.filterCurrentAisle(id);

                self.setOptionOfProduct(self.current_aisle.rd, self.current_aisle.as, self.current_aisle.axis); // 设置select选项

                if( !self.current_aisle.typed_product_id ) return;

                self.product_type = self.current_aisle.product_type;

                $('.product_type_select').val(self.current_aisle.product_type).trigger('change');

                self.selected_product_id = self.current_aisle.typed_product_id;

                $('.product_select').val(self.current_aisle.typed_product_id).trigger('change');

                // if( !self.current_aisle.color ) return;

                if( !self.isTransparentContactLens && !self.isNursingSupply ){  // 护理商品隐形眼镜
                    self.setColorOption();
                }

            },

            /**
             *  设置颜色的选项
             *  @return {undefined}
             */
            setColorOption: function () {
                var self = this;
                this.selected_color_id = this.current_aisle.color.id;

                this.getProductColor( this.current_aisle.typed_product_id,this.current_aisle.product_type )
                    .then(function(succeed){

                        if(succeed){

                            $('.color_select').val(self.current_aisle.color.id).trigger('change');

                        }

                    });
            },

            //根据商品拿到该商品对应的所有颜色
            getProductColor : function getProductColor( id , type ) {

                var self = this;

                var params = {

                    product_id : id,

                    product_type : type

                };

                App.blockUI('#product-form');

                return ProductColorResource.index( params )
                                            .then(function(res){

                                                if( parseInt(res.data.code) === 0 ){

                                                    self.colors = res.data.colors;

                                                    self.current_product_has_rd = !!res.data.has_rd;

                                                    App.unblockUI('#product-form');

                                                    return true;

                                                }else {

                                                    App.unblockUI('#product-form');

                                                    alert(res.data.error);

                                                }

                                            })
                                            .catch(function(err){

                                                App.unblockUI('#product-form');

                                                alert('请求颜色列表异常，请重试！');

                                            })

            },
            //过滤出当前货道数据的方法
            filterCurrentAisle : function filterCurrentAisle( id ) {

                var self = this;

                self.selected_machine_aisles.forEach(function(item){

                    item.forEach(function(column){

                        if(column.aisle_id == id) {

                            self.current_aisle = column;

                        }

                    });

                });

            },
            //确认货物
            confirmAisle : function confirmAisle() {

                var self = this;


                if( self.current_aisle.typed_product_id != self.selected_product_id ) {

                    self.current_aisle.typed_product_id = parseInt(self.selected_product_id);

                    if( self.current_aisle.current_count != 0 ) {

                        self.current_aisle.current_count = 0;

                    }

                }

                if( self.current_aisle.product_type != self.product_type ) {

                    self.current_aisle.product_type = self.product_type;

                    if( self.current_aisle.current_count != 0 ) {

                        self.current_aisle.current_count = 0;

                    }

                }

                if( !self.isTransparentContactLens && !self.isNursingSupply ) {

                    // self.current_aisle.color是null时。
                    if( typeof self.current_aisle.color === 'object' && !self.current_aisle.color ){

                        self.current_aisle.color = { id: '' }

                    }

                    if( self.current_aisle.color.id != self.selected_color_id ) {

                        self.current_aisle.color.id = self.selected_color_id;

                        if( self.current_aisle.current_count != 0 ) {

                            self.current_aisle.current_count = 0;

                        }

                    }

                }


                if ( self.current_aisle.rd !== self.selected_rd ){

                    this.current_aisle.rd = self.selected_rd;

                    if( self.current_aisle.current_count != 0 ) {

                        self.current_aisle.current_count = 0;

                    }

                }

                if ( self.current_aisle.as !== self.selected_as  ){

                    self.current_aisle.as = self.selected_as;

                    if( self.current_aisle.current_count != 0 ) {

                        self.current_aisle.current_count = 0;

                    }

                }

                if ( self.current_aisle.axis !== self.selected_axis ){

                    self.current_aisle.axis = self.selected_axis;

                    if( self.current_aisle.current_count != 0 ) {

                        self.current_aisle.current_count = 0;

                    }

                }

                if( self.hasRd ){ // 如果当前商品存在rd，设置货道色has_rd =1
                    self.current_aisle.has_rd = 1;
                }

                var current_product = self.all_products[self.product_type].filter(function(item){

                    return item.id == self.selected_product_id;

                })[0];

                self.current_aisle.should_add = self.current_aisle.max_count - self.current_aisle.current_count;

                self.current_aisle.img = current_product.thumb_img;

                $('.close').trigger('click');

            },


            //确认生成补货清单
            confirmReplenishment : function confirmReplenishment(){

                if( this.selected_replenishment_id === '' ){
                    alert('请选择补货员');
                    return;
                }

                var self = this;

                App.blockUI('#replenishment_info');

                var post_data = {

                    vendor_id : this.selected_machine_id,

                    vendor_replenishment_id : this.selected_replenishment_id,

                    aisles : this.formatParams(this.selected_machine_aisles)
                    // aisles : this.selected_machine_aisles

                };

                ReplenishResource.store( post_data )
                                .then(function(res){

                                    if( parseInt(res.data.code) === 0 ){

                                        App.unblockUI('#replenishment_info');

                                        alert('成功生成补货清单！');

                                        // 请求列表
                                        self.listRequest();

                                    }else{

                                        App.unblockUI('#replenishment_info');

                                        alert(res.data.error);

                                    }

                                })
                                .catch(function(err){

                                    App.unblockUI('#replenishment_info');

                                    alert('网络异常，请重试！');

                                })

            },

            /**
             *  格式化货道
             */
            formatParams: function (aisle) {
                for( var row=0; row<aisle.length; row++ ){
                    for (var column=0; column< aisle[row].length; column++ ){

                        if(this.isEmpty( aisle[row][column].rd )){
                            aisle[row][column].rd = null;
                        }

                        if(this.isEmpty( aisle[row][column].as )){
                            aisle[row][column].as = null;
                        }

                        if(this.isEmpty( aisle[row][column].axis )){
                            aisle[row][column].axis = null;
                        }

                        switch (aisle[row][column].product_type){
                            case "Glass":
                                aisle[row][column] = this.formatGlassParams(aisle[row][column]);
                                break;
                            case "TransparentContactLens" :
                                aisle[row][column] = this.formatContactLens(aisle[row][column]);
                                break;
                            case "BeautyContactLens" :
                                aisle[row][column] = this.formatContactLens(aisle[row][column]);
                                break;
                            case "NursingSupply" :
                                aisle[row][column] = this.formatNursingSupply(aisle[row][column]);
                                break;
                        }

                    }
                }
                return aisle;
            },

            /**
             * 处理glass类型返回的参数
             * @param product
             * @return {*}
             */
            formatGlassParams: function (product) {
                if( !product.has_rd ){
                   product.rd = null;
                }
                return product;
            },

            /**
             * 处理隐形眼镜类型返回的参数
             * @param product
             * @return {*}
             */
            formatContactLens: function (product) {
                product.axis = null;
                product.as = null;
                return product;
            },

            /**
             * 处理护理类型类型返回的参数
             * @param product
             * @return {*}
             */
            formatNursingSupply: function (product) {
                product.axis = null;
                product.as = null;
                product.rd = null;
                return product;
            },

            //导出补货清单Excel表的方法
            getExcel : function getExcel(){

                window.location.href = API_LIST.REPLENISH_EXCEL + '?id=' + this.selected_task_id;

            },
            //请求货道信息的方法
            aisleRequest : function aisleRequest( id ) {


                App.blockUI('#replenishment_info');

                var self = this;

                self.selected_machine_aisles = null;

                return ReplenishResource.edit( id )
                    .then(function(res){

                        if( parseInt(res.data.code) === 0 ){

                            App.unblockUI('#replenishment_info');

                            self.selected_machine_aisles = res.data.aisles;

                            return true;

                        }else{

                            App.unblockUI('#replenishment_info');

                            alert(res.error);

                            return false;

                        }

                    })
                    .catch(function(err){

                        App.unblockUI('#replenishment_info');

                        alert('请求货道信息异常，请重试！');

                    });

            },
            //改变页数的时候出发的函数
            pageChange : function pageChange(val){

                this.tasks.page = val;

                this.listRequest();

            },
            //改变每页显示数时触发的函数
            sizeChange : function sizeChange(val){

                this.tasks.per_page = val;

                this.listRequest();

            },
            //请求清单列表的方法
            listRequest : function listRequest(){

                App.blockUI('#replenishment_list');

                var self = this;

                var params = {

                    per_page : self.tasks.per_page,

                    page : self.tasks.page

                };

                ReplenishResource.index( params )
                                .then(function(res){

                                    if( parseInt(res.data.code) === 0 ){

                                        self.tasks = res.data.tasks;

                                        self.tasks.per_page = parseInt(self.tasks.per_page);

                                        App.unblockUI('#replenishment_list');

                                    }else {

                                        App.unblockUI('#replenishment_list');

                                        alert( res.data.error );

                                    }

                                })
                                .catch(function(err){

                                    console.log(err);

                                    App.unblockUI('#replenishment_list');

                                    alert('网络异常，请重试！');

                                })

            },
            //查看清单详情
            watchListDetail : function watchListDetail( id ){

                var self = this;

                App.blockUI('#list-form');

                ReplenishResource.show(id)
                                .then(function(res){

                                    if( parseInt(res.data.code) === 0 ){

                                        self.selected_task_id = id;

                                        self.task_details = res.data.aisles;

                                        App.unblockUI('#list-form');

                                    }else {

                                        App.unblockUI('#list-form');

                                        alert(res.data.error);

                                    }

                                })
                                .catch(function(err){

                                    console.log(err);

                                    App.unblockUI('#list-form');

                                    alert('网络异常，请重试！');

                                })

            },
            //删除清单
            deleteList : function deleteList( id ){

                if(confirm('确定要删除吗？')){

                    var self = this;

                    App.blockUI('#replenishment_list');

                    ReplenishResource.destroy( id )
                        .then(function(res){

                            if( parseInt(res.data.code) === 0 ){

                                App.unblockUI('#replenishment_list');

                                alert('删除成功！');

                                self.listRequest();

                            }else {

                                App.unblockUI('#replenishment_list');

                                alert(res.data.error);

                            }

                        })
                        .catch(function(err){

                            console.log(err);

                            App.unblockUI('#replenishment_list');

                            alert('网络异常，请重试！');

                        })

                }else {

                    return;

                }
            },
            //获取数据
            initData : function initData() {

                var self = this;

                return ReplenishResource.create()
                    .then(function( res ){

                        var data = res.data;

                        if( parseInt(data.code) === 0 ){

                            self.all_products = data.all_products;

                            self.machine_infos = data.vendor_machines;

                            self.replenishment_clerks = data.replenishment_clerks;

                            self.selected_machine_id = data.vendor_machines[0].id;

                            self.opto = data.opto;

                            self.aisleRequest(self.selected_machine_id);

                            return true;

                        }else {

                            alert(res.data.error);

                        }

                    })
                    .catch(function( err ){

                        alert("初始化数据异常，请重试！");

                    })

            }
        }
    })

}();